//
//  PlanPeopleVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/30.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "PlanPeopleVC.h"
#import "PlanPeopleHeadView.h"
#import "PlanVM.h"
#import "MyVM.h"
#import "UserInfoModel.h"
#import "LabCell.h"
#import "GradesModel.h"
#import "OtherInfoVC.h"
#import "CommentDetailVC.h"
#import "CommentListVC.h"
#import "CommentsTextView.h"
#import "ExceptionalVC.h"
#import "PlanPeopleTotalVC.h"
#import "CommentVM.h"
#import "PlanPayView.h"
#import "PlanPeopleNewVC.h"
#import "OnlineTop_up.h"
#import "PredictRecordCell.h"
#import "PlanPeopleCenterView.h"

#import "InformationVM.h"
//#import "ShareView.h"
@interface PlanPeopleVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UserInfoModel *userModel;
@property (nonatomic ,strong) PlanPeopleHeadView  *headView;

@property (nonatomic ,strong) PlanPeopleCenterView  *centerView;

@property (nonatomic ,strong) BetModel         *betModel;
@property (nonatomic ,strong) NSMutableArray *dataArr;



@property (nonatomic ,strong) NSMutableArray           *arr1;
@property (nonatomic ,strong) NSMutableArray           *arr2;
@property (nonatomic ,strong) NSMutableArray           *arr3;

@property (nonatomic ,strong) NSMutableArray           *colArr1;
@property (nonatomic ,strong) NSMutableArray           *colArr2;
@property (nonatomic ,strong) NSMutableArray           *colArr3;

@end

@implementation PlanPeopleVC{
    NSString    *selectModelId;
    
    NSString       *sendStr;
    QXLable     *labCount;
    
    
    dispatch_source_t _timer;

}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=DEFAULTBGCOLOR;
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
//    [self.tableView reloadData];
//    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
//    self.navigationItem.rightBarButtonItem=rightItem;
 
    self.arr1 = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    self.arr3 = [NSMutableArray array];
    self.colArr1 = [NSMutableArray array];
    self.colArr2 = [NSMutableArray array];
    self.colArr3 = [NSMutableArray array];

    [self setupHeadView];
    
    [self setupCenterView];

    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
            [self getAdvertising];
    });
    
    
    
    [self startTimer];
}

-(void)planPeopleCenterView_collectionViewAction:(NSNotification *)notification{
    NSLog(@"%@",notification.userInfo);
    
    [self getStatisticsAndList];
}
//取消定时器
- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}
#pragma mark - 启动定时器
- (void)startTimer{
    
    
    [self cancleTimer];
    [self.headView cancleTimer];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),20.0*NSEC_PER_SEC, 0);

    dispatch_source_set_event_handler(_timer, ^{
        
//        NSLog(@"-11---%@---%@",self.headView.openTime,self.lotteryModel.lType);
//
        [self.headView setLType: self.lotteryModel.lType];
        [self getStatisticsAndList];
        
        dispatch_async(dispatch_get_main_queue(), ^{

            [self.tableView reloadData];
        });
    });
    
    
    
    dispatch_resume(_timer);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.headView cancleTimer];

}

- (void)backClick{
    [super backClick];
    [self cancleTimer];
    [self.headView cancleTimer];
    
    
}

#pragma mark -- 分享
//- (void)share{
//    ShareView *shareView=[[ShareView alloc]init];
//    [shareView show];
//}

#pragma mark -- 打赏
- (void)exceptional{
    ExceptionalVC *vc=[[ExceptionalVC alloc]init];
    vc.model=self.model;
    vc.lotteryModel=self.lotteryModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- 查看总成绩
- (void)results{
    PlanPeopleTotalVC *vc=[[PlanPeopleTotalVC alloc]init];
    vc.lotteryModel=self.lotteryModel;
    vc.model=self.model;
    vc.title=self.title;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- 查看预测号码
- (void)lookNew{
    if (self.dataArr.count <= 0) {
        return;
    }
    
    //判断登录
    if ([UserModel userModel].UserId==0) {
        
        [[BaseVM manage] login];
        
        return;
    }
    
    WS(weakSelf);
    BetModel *newModel=self.dataArr[0];
    [[PlanVM manage] getLastPlayWithUid:self.model.UserId andLType:[self.lotteryModel.lType integerValue] andPlayName:self.playName andIssue:self.headView.lotteryModel.CurrentIssue Success:^(id returnValue) {
        BetModel *model =[BetModel mj_objectWithKeyValues:returnValue];
        newModel.BetNum=model.BetNum;
        [weakSelf.dataArr replaceObjectAtIndex:0 withObject:newModel];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        if ([errorMessage intValue]==60018) {
            UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:@"金币不足" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
            UIAlertAction *goAction=[UIAlertAction actionWithTitle:@"前往充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                OnlineTop_up *vc=[[OnlineTop_up alloc]init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }];
            [alertCtrl addAction:cancleAction];
            [alertCtrl addAction:goAction];
            [weakSelf presentViewController:alertCtrl animated:YES completion:nil];
        }
    }];
}

#pragma mark -- 获取用户已查询过的预测号码
- (void)getLastPlan{
    
    if ([UserModel userModel].UserId==0) {
        return;
    }
    WS(weakSelf);
    BetModel *newModel=self.dataArr[0];
    
    if (self.headView.lotteryModel.CurrentIssue!=nil) {
        [[PlanVM manage] getLastPlanWithUid:self.model.UserId andLType:[self.lotteryModel.lType integerValue] andPlayName:self.playName andIssue:self.headView.lotteryModel.CurrentIssue Success:^(id returnValue) {
            newModel.BetNum=returnValue;
            
            
            [weakSelf.dataArr replaceObjectAtIndex:0 withObject:newModel];
            
            [weakSelf.tableView reloadData];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }
    
    
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count+1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PredictRecordCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PredictRecordCell" forIndexPath:indexPath];
    if (indexPath.row==0) {
        [cell setModel:nil andRow:0];
    }else{
        [cell setModel:self.dataArr[indexPath.row-1] andRow:indexPath.row];
    }
    WS(weakSelf);
    cell.lookNew = ^{
        [weakSelf lookNew];
    };
    return cell;
}

- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.backgroundColor = DEFAULTBGCOLOR;
        _tableView.dataSource=self;
        _tableView.delegate=self;
        [_tableView registerClass:[PredictRecordCell class] forCellReuseIdentifier:@"PredictRecordCell"];
//        _tableView.rowHeight=UITableViewAutomaticDimension;
//        _tableView.estimatedRowHeight=200;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor=[UIColor whiteColor];
        _tableView.layer.masksToBounds=YES;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.equalTo(weakSelf.view);
            make.top.equalTo(self.headView.mas_bottom).with.offset(real_size(5));
//            make.edges.equalTo(weakSelf.view);
        }];
        
        _tableView.tableHeaderView = self.centerView;
    }
    return _tableView;
}



- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (BetModel *)betModel{
    if (!_betModel) {
        _betModel=[[BetModel alloc]init];
        _betModel.Issue=@"";
    }
    return _betModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    NSLog(@"planpeopleVC   销毁");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PlanPeopleCenterView_collectionView" object:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark ---new

-(void)setupCenterView{
    self.centerView=[[PlanPeopleCenterView alloc]init];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(planPeopleCenterView_collectionViewAction:) name:@"PlanPeopleCenterView_collectionView" object:nil];
    
    _centerView.frame =CGRectMake(0, 0, SCREEN_WIDTH, real_size(90)+40*(self.arr1.count +self.arr2.count+self.arr3.count)-40*(ceil(self.colArr1.count/2.0)+ceil(self.colArr2.count/2.0)+ceil(self.colArr3.count/2.0)));
}

-(void)setupHeadView{
    
    WS(weakSelf);
    self.headView=[[PlanPeopleHeadView alloc]init];
    self.headView.userId=self.model.UserId;
    
    self.headView.lType=self.lotteryModel.lType;
    
    self.headView.playName=self.playName;
    self.headView.clickExceptional = ^{
        [weakSelf exceptional];
    };
    
    [self.view addSubview:self.headView];
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(@(real_size(130)));
    }];
//    _headView.updateHeightBlock = ^(NSInteger count) {
//
//        CGFloat height=100+count*32;
//
//        [weakSelf.headView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(@(real_size(height)));
//        }];
//    };
    
    _headView.returnDataBlock = ^(NSString *str) {
        
        weakSelf.betModel.Issue = str;
        
        [weakSelf getStatisticsAndList];
    };
    
    
    
}

#pragma mark -- 获取广告
- (void)getAdvertising{
    WS(weakSelf);

    
    [[InformationVM manage] getAdvertWithLocation:@"0" andType:8 Success:^(id returnValue) {

        
        [weakSelf.arr1 removeAllObjects];
        [weakSelf.arr2 removeAllObjects];
        [weakSelf.arr3 removeAllObjects];
        [weakSelf.colArr1 removeAllObjects];
        [weakSelf.colArr2 removeAllObjects];
        [weakSelf.colArr3 removeAllObjects];
       
        for (AdvertisingModel *model in returnValue) {
            if (model.Layer == 1) {
                [weakSelf.arr1 addObject:model];
                if (model.IsDisplay) {
                     [weakSelf.colArr1 addObject:model];
                }
                
            }
            if (model.Layer == 2) {
                [weakSelf.arr2 addObject:model];
                if (model.IsDisplay) {
                    [weakSelf.colArr2 addObject:model];
                }
            }
            if (model.Layer == 3) {
                [weakSelf.arr3 addObject:model];
                if (model.IsDisplay) {
                    [weakSelf.colArr3 addObject:model];
                }
            }
        }
        
        weakSelf.centerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, real_size(90)+40*(self.arr1.count +self.arr2.count+self.arr3.count)-40*(ceil(self.colArr1.count/2.0)+ceil(self.colArr2.count/2.0)+ceil(self.colArr3.count/2.0)));

        [weakSelf.centerView setModelArr1:weakSelf.arr1 AndRowCount:weakSelf.arr1.count-(NSInteger)ceil(weakSelf.colArr1.count/2.0)];
        [weakSelf.centerView setModelArr2:weakSelf.arr2 AndRowCount:weakSelf.arr2.count-(NSInteger)ceil(weakSelf.colArr2.count/2.0)];
        [weakSelf.centerView setModelArr3:weakSelf.arr3 AndRowCount:weakSelf.arr3.count-(NSInteger)ceil(weakSelf.colArr3.count/2.0)];
        
        [weakSelf.tableView reloadData];

        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}




- (void)getStatisticsAndList{
    NSInteger pageSize=10;
    if (self.centerView.selected==1) {
        pageSize=20;
    }else if (self.centerView.selected==2){
        pageSize=30;
    }else if (self.centerView.selected==3){
        pageSize=50;
    }else if (self.centerView.selected==4){
        pageSize=100;
    }
    WS(weakSelf);
    [[MyVM manage] getStatisticsAndListWithUid:self.model.UserId andLType:[self.model.lType integerValue] andPlayName:self.playName andPageSize:pageSize andSuccess:^(id returnValue) {
        NSArray *arr=[BetModel mj_objectArrayWithKeyValuesArray:[returnValue objectForKey:@"LotteryStatisticsList"]];
        

            NSInteger lType=[weakSelf.headView.lotteryModel.LType integerValue];
            NSString *num=weakSelf.headView.lotteryModel.CurrentIssue;
            if ((lType==10||lType==39||lType==54||lType==63||lType==65)) {
                num=weakSelf.headView.lotteryModel.CurrentIssue;

            }else if ((lType>=51&&lType<=59)||(lType>=15&&lType<=37)||(lType>=38&&lType<=50)){
                num=[weakSelf.headView.lotteryModel.CurrentIssue substringWithRange:NSMakeRange(weakSelf.headView.lotteryModel.CurrentIssue.length-2, 2)];
            }else{
                num=[weakSelf.headView.lotteryModel.CurrentIssue substringWithRange:NSMakeRange(weakSelf.headView.lotteryModel.CurrentIssue.length-3, 3)];
            }
//MARK:/*----******----------------------------------------------------**/
//        self.betModel;
        [weakSelf.dataArr removeAllObjects];
        

            if (![weakSelf.betModel.Issue isEqualToString:num] &&num !=nil) {
                weakSelf.betModel.Issue=num;
                weakSelf.betModel.BetNum=@"";
            }
  

       
        [weakSelf.dataArr addObject:weakSelf.betModel];
        [weakSelf.dataArr addObjectsFromArray:arr];

        weakSelf.centerView.predictedStr =[returnValue objectForKey:@"Desc"];

        dispatch_async(dispatch_get_main_queue(), ^{

            [weakSelf.tableView reloadData];

        });
//
        [weakSelf getLastPlan];
        
        /*------*/
        
        
//
        
    


    } andFail:^(NSString *errorMessage, NSError *error) {

    }];
}


#pragma mark -- headView 转移





@end
